﻿using AngleSharp.Html.Parser;
using SpiderPlatform.Dao;
using SpiderPlatform.Entity;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
namespace SpiderPlatform.Detail
{
    public class OscartDetailService
    {      
        ItemDao itemDao = new ItemDao();
        HtmlParser htmlParser = new HtmlParser();
        public void doWork()
        {
            var list = itemDao.QueryChannelItemRealTime(2);
            //list = list.Take(1).ToList();
            List<Task> taskList = new List<Task>();
            List<Task> taskList2 = new List<Task>();
            foreach (var item in list)
            {
                taskList.Add(Task.Factory.StartNew(async () =>
                {
                    Logger.Info("process " + item.channel_sku);
                    var t2= GetProductAsync(item.channel_sku);
                    taskList2.Add(t2);
                    var data =await t2;
                    item.is_instock = data.is_instock;
                    item.score = 0;
                    item.reviews = 0;
                    item.price = decimal.Parse(data.price.TrimStart('$'));
                }));
            }
            Task.WaitAll(taskList.ToArray());
            Task.WaitAll(taskList2.ToArray());
            Logger.Info("...load data done...");
            itemDao.UpdateChannelItemRealTime(list);
            Logger.Info("...all done...");
        }
       
        private async Task<OscartEntity> GetProductAsync(string channelSku)
        {
            OscartEntity entity = new OscartEntity();
            HttpClient client = new HttpClient();
            var res = await client.GetAsync($"https://www.oscart.com/products/{channelSku}");
           // var res = await client.GetAsync($"https://www.oscart.com/products/k64bo0gqafye");
            try
            {
                if (res.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    string data = await res.Content.ReadAsStringAsync();
                    if (!string.IsNullOrEmpty(data))
                    {
                        var dom = htmlParser.ParseDocument(data);
                        var reviews = dom.QuerySelector("div.item-price .total-reviews");
                        if (reviews == null)
                        {
                            Logger.Info($"{channelSku}=>商品下架");
                            entity.is_instock = 0;
                            return entity;
                        }
                        entity.reviews = reviews.InnerHtml;
                        entity.price = dom.QuerySelector("div.item-price .item-price-now").InnerHtml;
                        entity.old_price = dom.QuerySelector("div.item-price .item-price-was")?.InnerHtml;
                        var buy = dom.QuerySelector("div.msg-title");
                        if (buy != null && buy.InnerHtml.Trim() == "售罄")
                        {
                            entity.is_instock = 0;
                        }
                        else
                        {
                            entity.is_instock = 1;
                        }
                        Logger.Info($"{channelSku}=>商品正常");
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error($"{channelSku}=>{ex.Message}");               
            }
            return entity;
        }
    }
}
